package com.ssm.basis.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @see RestTemplateAutoConfiguration
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
class RestTemplateConfig {
    @Bean
    RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) {
        return restTemplateBuilder
            .requestFactory(() -> new BufferingClientHttpRequestFactory(restTemplateBuilder.buildRequestFactory()))
            // .setConnectTimeout(Duration.ofSeconds(5))
            // .setReadTimeout(Duration.ofSeconds(5))
            // .additionalMessageConverters(new MappingJackson2HttpMessageConverter() {
            //     { // 创建一个新的转换器，解析微信的 [text/plain]
            //         setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_PLAIN));
            //         // defaultObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
            //     }
            // })
            .additionalInterceptors((request, body, execution) -> {
                String headStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(request.getHeaders());
                String bodyStr = new String(body);
                // if (MediaType.APPLICATION_JSON.equals(request.getHeaders().getContentType()) || MediaType.APPLICATION_JSON_UTF8.equals(request.getHeaders().getContentType())) {
                //     bodyStr = objectMapper.readTree(body).toPrettyString();
                // }
                log.info("request: {} {}\n{}\n{}", request.getMethodValue(), request.getURI(), headStr, bodyStr);
                ClientHttpResponse response = execution.execute(request, body);
                StringBuilder responseBodyStringBuilder = new StringBuilder();
                try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody()))) {
                    while ((bodyStr = bufferedReader.readLine()) != null) responseBodyStringBuilder.append(bodyStr);
                }
                headStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getHeaders());
                bodyStr = responseBodyStringBuilder.toString();
                // if (MediaType.APPLICATION_JSON.equals(response.getHeaders().getContentType()) || MediaType.APPLICATION_JSON_UTF8.equals(response.getHeaders().getContentType())) {
                //     bodyStr = objectMapper.readTree(responseBodyStringBuilder.toString()).toPrettyString();
                // }
                log.info("response: {}\n{}\n{}", response.getStatusCode(), headStr, bodyStr);
                return response;
            }).build();
    }
}